const {
  $Message
} = require('/component/iView/base/index');
const mtjwxsdk = require('./utils/mtj-wx-sdk.js');

App({
  globalData: {
    userInfo: {
      avatarUrl: "./user-unlogin.png",
      nickName: "昵称",
      companyId: null,
      deptId: null
    },
   baseAPI: "https://exam.lrltd.cn",
    //baseAPI: "http://127.0.0.1:8000",
    pageSize: 10
  },
  onLaunch: function() {
    let _this = this
    let token = wx.getStorageSync('Authorization')
    if (null == token || token == '') {
      wx.login({
        success(wxres) {
          if (wxres.code) {
            _this.formPost('/api/wx/user/login', {
              "code": wxres.code
            }).then(res => {
              if (res.code == 20000) {
                wx.setStorageSync('Authorization', res.data)
                wx.reLaunch({
                  url: '/pages/index/index',
                });
              } else if (res.code == 2) {
                wx.reLaunch({
                  url: '/pages/user/bind/index',
                });
              } else {
                _this.message(res.message, 'error')
              }
            }).catch(e => {
              _this.message(e, 'error')
            })
          } else {
            _this.message(res.errMsg, 'error')
          }
        }
      })
    }
  },
  message: function(content, type) {
    $Message({
      content: content,
      type: type
    });
  },
  formPost: function(url, data) {
    let _this = this
    return new Promise(function(resolve, reject) {
      wx.showNavigationBarLoading();
      wx.request({
        url: _this.globalData.baseAPI + url,
        header: {
          'content-type': 'application/json',
          'Authorization': wx.getStorageSync('Authorization')
        },
        method: 'POST',
        data,
        success(res) {
          if (res.data.code !== 20000) {
            reject('网络出错')
            return false;
          }
          resolve(res.data)
        },
        fail(res) {
          reject(res.errMsg)
          return false;
        },
        complete(res) {
          wx.hideNavigationBarLoading();
        }
      })
    })
  }
})